from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from user.models import User
from user.serializers import UserModelSerializer


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    class Meta:
        model = User
        fields = "__all__"

    """
    自定义登录认证，使用自有用户表
    username、password这两个字段为必传字段因为 DRF 要检查这些字段是否有效
    username_field = 'phone_number'  这是重命名了，username必传字段设置为了phone_number字段必传
    phone_number = serializers.CharField(required=False) # 这个是设置了自定义的字段是否必传
    """

    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")
        user = User.objects.get(username=username, password=password)
        if not user:
            result = {
                "code": 400,
                "msg": "账号或密码不正确！",
                "data": None
            }
            return result
        # if user.role != 'ADMIN':  # 判断是否允许登录后台
        #     result = {
        #         "code": 400,
        #         "msg": "您没有权限登录后台！",
        #         "data": None
        #     }
        #     return result
        refresh = self.get_token(user)
        data = {'user': UserModelSerializer(user).data, "token": str(refresh.access_token)}
        result = {
            "code": 200,
            "msg": "登录成功！",
            "data": data
        }
        return result


class LoginView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer
